import {
  PdfJs,
  SpecialZoomLevel,
  Spinner,
  Store,
  StoreHandler,
} from "../../core";

import StoreProps from "./StoreProps";
import BookmarkLoader from "./BookmarkLoader";
import { FC, useEffect, useState } from "react";

const BookmarkListWithStore: FC<{
  store: Store<StoreProps>;
}> = ({ store }) => {
  const [currentDoc, setCurrentDoc] = useState(store.get("doc"));

  const handleDocumentChanged: StoreHandler<PdfJs.PdfDocument> = (
    doc: PdfJs.PdfDocument
  ) => {
    setCurrentDoc(doc);
  };

  const jump = (
    pageIndex: number,
    bottomOffset: number,
    scaleTo: number | SpecialZoomLevel
  ) => {
    const jumpToDestination = store.get("jumpToDestination");
    if (jumpToDestination) {
      jumpToDestination(pageIndex, bottomOffset, 0, scaleTo);
    }
  };

  useEffect(() => {
    store.subscribe("doc", handleDocumentChanged);

    return () => {
      store.unsubscribe("doc", handleDocumentChanged);
    };
  }, []);

  return currentDoc ? (
    <BookmarkLoader doc={currentDoc} onJumpToDest={jump} />
  ) : (
    <div className="rpv-bookmark__loader">
      <Spinner />
    </div>
  );
};

export default BookmarkListWithStore;
